<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="所属区域" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="areaId">
              <j-select-area placeholder="请选择区域" v-model="model.areaId" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="村庄名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="villageName">
              <a-input v-model="model.villageName" placeholder="请输入村庄名称"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="经度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="longitude">
              <a-input-number v-model="model.longitude" placeholder="请输入经度" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="纬度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="latitude">
              <a-input-number v-model="model.latitude" placeholder="请输入纬度" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="关联企业" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="enterpriseId">
              <a-select
                v-model="model.enterpriseId"
                placeholder="请选择企业"
                style="width: 100%"
                @change="handleChange"
              >
                <a-select-option :value="undefined">请选择</a-select-option>
                <a-select-option v-for="item in enterpriseList" :key="item.id" :value="item.id">
                  {{ item.enterpriseName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="model.enterpriseId">
            <a-form-model-item label="负责人" :labelCol="labelCol" :wrapperCol="wrapperCol" class="ant-form-item-required" prop="operatorLdrIds">
              <a-select
                v-model="opList"
                mode="multiple"
                placeholder="请选择负责人"
                style="width: 100%"
                @change="handleChange2"
              >
                <a-select-option v-for="item in operatorList" :key="item.id" :value="item.id">
                  {{ item.operatorName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="model.enterpriseId">
            <a-form-model-item label="运维人员" :labelCol="labelCol" :wrapperCol="wrapperCol" class="ant-form-item-required" prop="operatorIds">
              <a-select
                v-model="opList2"
                mode="multiple"
                placeholder="请选择运维人员"
                style="width: 100%"
                @change="handleChange3"
              >
                <a-select-option v-for="item in operatorList" :key="item.id" :value="item.id">
                  {{ item.operatorName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="排水户" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="farmersNum">
              <a-input v-model="model.farmersNum" placeholder="请输入农户数量"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="接入终端" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="terminalNum">
              <a-input v-model="model.terminalNum" placeholder="请输入接入终端农户数"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="管网长度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="pipLength">
              <a-input v-model="model.pipLength" placeholder="请输入管网长度"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="村庄属性" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="attr">
              <j-dict-select-tag
                type="list"
                v-model="model.attr"
                dictCode="nw_vill_attr"
                placeholder="请选择村庄属性"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="关联终端" class="ant-form-item-required" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="terminalId">
              <a-select
                v-model="model.terminalId"
                show-search
                allowClear
                placeholder="请选择"
                :default-active-first-option="false"
                :show-arrow="false"
                :not-found-content="null"
                option-filter-prop="children"
                @change="handleTerminalSelected"
              >
                <!-- 显示终端名称+编号 -->
                <a-select-option :value="undefined">请选择</a-select-option>
                <a-select-option v-for="item in terminalList" :key="item.value" :value="item.value">
                  {{ item.label }}
                </a-select-option>
              </a-select>
<!--              <a-input v-model="model.terminalId" placeholder="请输入终端编号"></a-input>-->
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="村庄类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="villageType">
              <a-select v-model="model.villageType">
                <a-select-option :value="1">行政村</a-select-option>
                <a-select-option :value="2">自然村</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="村庄航拍图" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="aerialPhoto">
              <!-- <a-input v-model="model.picData" placeholder="请输入图片数据"></a-input> -->
              <j-upload type="1"  fileType="all"   :number="4" v-model="model.aerialPhoto"></j-upload>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="雨水图" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="rainPicData">
              <!-- <a-input v-model="model.picData" placeholder="请输入图片数据"></a-input> -->
              <j-upload type="1" bizPath="images" fileType="image"   :number="4" v-model="model.rainPicData"></j-upload>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="污水图" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="dirtyPicData">
              <!-- <a-input v-model="model.picData" placeholder="请输入图片数据"></a-input> -->
              <j-upload type="1" bizPath="images" fileType="image"  :number="4" v-model="model.dirtyPicData"></j-upload>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="排水户类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="villageType">
              <div v-for="(i,index) in arr" :key="index" style="display: flex">
                <div style="width: 25%">{{i.type==1?'农户':i.type==2?'农家乐':''}}</div><a-input-number v-model="i.num" /><span style="margin-left: 10px">户</span>
              </div>
            </a-form-model-item>
          </a-col>
<!--          <a-col :span="12">-->
<!--            <a-button type="primary" @click="generateQRCode">重新生成二维码</a-button>-->
<!--          </a-col>-->
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  // import { validateDuplicateValue } from '@/utils/util
  export default {
    name: 'VillageForm',
    components: {
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        arr:[
          {
            type:1,
            num:'',
          },
          {
            type:2,
            num:'',
          }
        ],
        operatorList:[],
        opList:[],
        opList2:[],
        enterpriseList:[],
        terminalList:[],
        // idsValue:[],
        model:{},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        validatorRules: {
          areaId: [{ required: true, message: '请选择所属区域!' }],
          villageName: [{ required: true, message: '请输入村庄名称!' }],
          longitude: [{ required: true, message: '请输入经度!' }],
          latitude: [{ required: true, message: '请输入纬度!' }],
          enterpriseId: [{ required: true, message: '请选择企业!' }],
          farmersNum: [{ required: true, message: '请输入排水户!' }],
          terminalNum: [{ required: true, message: '请输入接入终端数!' }],
          attr: [{ required: true, message: '请选择村庄属性!' }],
          // terminalId: [{ required: true, message: '请输入关联农污终端编号!' }],
        },
        url: {
          add: "/ps/village/add",
          edit: "/ps/village/edit",
          queryById: "/ps/village/queryById"
        }
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      this.getEnterpriseList()
      this.getTerminalList()
      // this.getFarmersTypesList('nw_farmers_type')
    },
    methods: {
      // // 获取管径类型枚举
      // async getFarmersTypesList(dictCode) {
      //   const res = await getAction(`/sys/dictItem/dictItemGet`,{dictCode})
      //   this.arr = (res.result || []).map((x) => {
      //     return {
      //       type: x.itemValue,
      //       num:''
      //     };
      //   });
      // },
     async generateQRCode(){
        const res = await getAction(`/ps/village/generateQRCode`,{urlCode:`https://zjhcjhnw.com/h5/#/?id=${this.model.id}`,text:this.model.villageName})
          console.log(res,'00000000000000')
         this.model.qr=res
      },
      handleTerminalSelected(terminalId) {
        console.log(terminalId)
      },
      async getTerminalList() {
        try {
          const res = await getAction(`/terminal/terminal/list`, { pageNo: 1, pageSize: 10000 })
          const terminalList = res.result.records || []
          this.terminalList = terminalList.map((terminal) => ({
            value: terminal.terminalId,
            label: `${terminal.terminalName}(${terminal.terminalId})`,
          }))
        } catch (error) {
          console.log(error)
        }
      },
      async getEnterpriseList() {
        const res = await getAction(`/ps/enterprise/list`)
        if (res.success) {
          this.enterpriseList= res.result.records
          // this.enValue=res.result.records[0].id
        }
      },
      handleChange(e){
        // console.log(e)
        this.model.enterpriseId= e
        this.opList=[]
        this.opList2=[]
        this.getOperatorIds(e)

      },
      handleChange2(e){
        console.log(e,'2222222222222')
        this.opList= e
      },
      handleChange3(e){
        console.log(e,'2222222222222')
        this.opList2= e
      },
      async getOperatorIds(id) {
        const res = await getAction(`/ps/operator/list`, { enterpriseId:id })
        if (res.success) {
          this.operatorList= res.result.records
        }
      },
      add () {
        this.edit(this.modelDefault);
      },
      edit (record) {
        console.log(record,'2025555555')
        this.model = Object.assign({}, record);
        this.opList=record.operatorLdrIds.split(",");
        this.opList2=record.operatorIds.split(",");
        this.visible = true;
        this.getOperatorIds(record.enterpriseId)
       if(record.farmersTypesList) this.arr=record.farmersTypesList
        console.log(this.arr,'8.5555555555555555')
      },
      submitForm () {
        console.log(this.arr,'33333333333333333')
        const that = this;
        const ids=this.opList.join(',')
        const ids2=this.opList2.join(',')
        // const allNum=this.arr.reduce((pre, cur) => pre + cur.num, 0);
        console.log(this.model.terminalId,'2222')
        // 触发表单验证
        if(ids==''){
          this.$message.error('请选择负责人!')
        }else if (ids2==''){
          this.$message.error('请选择运维人员!')
        }else {
          this.$refs.form.validate(valid => {
            if (valid) {
              that.confirmLoading = true;
              let httpurl = '';
              let method = '';
              if(!this.model.id){
                httpurl+=this.url.add;
                method = 'post';
              }else{
                httpurl+=this.url.edit;
                method = 'put';
              }
              const { terminalId } = this.model
              const params={...this.model,operatorLdrIds:ids,operatorIds:ids2,terminalId: terminalId ? terminalId : '',farmersTypesList:this.arr }
              httpAction(httpurl,params,method).then((res)=>{
                if(res.success){
                  that.$message.success(res.message);
                  that.$emit('ok');
                }else{
                  that.$message.warning(res.message);
                }
              }).finally(() => {
                that.confirmLoading = false;
              })
            }

          })
        }

      },
    }
  }
</script>
<style scoped>
.ant-form-item-required >>> label:before {
  display: inline-block;
  margin-right: 4px;
  color: #f5222d;
  font-size: 14px;
  font-family: SimSun, sans-serif;
  line-height: 1;
  content: '*';
}
</style>